package com.mcppro.aidatabase.service;

import com.mcppro.aidatabase.config.SiliconFlowConfig;
import com.mcppro.aidatabase.dto.SiliconFlowDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.List;

/**
 * 硅基流动AI服务实现
 * 
 * @author MCP Pro
 */
@Service
@Slf4j
public class SiliconFlowService {

    private final WebClient webClient;
    private final SiliconFlowConfig config;

    @Autowired
    public SiliconFlowService(SiliconFlowConfig config) {
        this.config = config;
        this.webClient = WebClient.builder()
                .baseUrl(config.getApiUrl())
                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + config.getApiKey())
                .build();
    }

    /**
     * 发送聊天请求到硅基流动AI
     * 
     * @param userMessage 用户消息
     * @param systemPrompt 系统提示词
     * @return AI响应
     */
    public Mono<String> chat(String userMessage, String systemPrompt) {
        log.debug("发送AI请求 - 用户消息: {}", userMessage);
        
        // 构建消息列表
        List<SiliconFlowDto.Message> messages = List.of(
                SiliconFlowDto.Message.system(systemPrompt),
                SiliconFlowDto.Message.user(userMessage)
        );

        // 构建请求
        SiliconFlowDto.ChatRequest request = new SiliconFlowDto.ChatRequest(
                config.getModel(),
                messages,
                config.getMaxTokens(),
                config.getTemperature(),
                false
        );

        return webClient.post()
                .bodyValue(request)
                .retrieve()
                .bodyToMono(SiliconFlowDto.ChatResponse.class)
                .timeout(Duration.ofMillis(config.getTimeout()))
                .map(response -> {
                    if (response.getChoices() != null && !response.getChoices().isEmpty()) {
                        String content = response.getChoices().get(0).getMessage().getContent();
                        log.debug("AI响应成功: {}", content);
                        return content;
                    }
                    throw new RuntimeException("AI响应为空");
                })
                .onErrorMap(WebClientResponseException.class, ex -> {
                    log.error("AI请求失败 - 状态码: {}, 响应: {}", ex.getStatusCode(), ex.getResponseBodyAsString());
                    return new RuntimeException("AI服务调用失败: " + ex.getMessage());
                })
                .onErrorMap(Exception.class, ex -> {
                    log.error("AI请求异常", ex);
                    return new RuntimeException("AI服务异常: " + ex.getMessage());
                });
    }

    /**
     * 简单聊天接口（使用默认系统提示词）
     * 
     * @param userMessage 用户消息
     * @return AI响应
     */
    public Mono<String> chat(String userMessage) {
        String defaultSystemPrompt = "你是一个专业的数据库管理助手，能够理解用户的自然语言请求并帮助操作数据库。";
        return chat(userMessage, defaultSystemPrompt);
    }

    /**
     * 测试AI服务连接
     * 
     * @return 测试结果
     */
    public Mono<Boolean> testConnection() {
        return chat("测试连接", "请回复'连接成功'")
                .map(response -> response.contains("连接成功") || response.contains("成功"))
                .onErrorReturn(false);
    }
}